<template>
  <view class="product-card" @click="goToDetail">
    <view class="product-image">
      <image :src="product.mainImage || '/static/images/default-product.png'" mode="aspectFill" class="product-img-inner" />
      <view v-if="product.isNew" class="new-tag">新品</view>
      <view v-if="product.discount" class="discount-tag">{{ product.discount }}折</view>
    </view>
    <view class="product-info">
      <view class="product-name">{{ product.name }}</view>
      <view class="product-desc">{{ product.description }}</view>
      <view class="product-tags" v-if="product.tags && product.tags.length">
        <text v-for="tag in product.tags.slice(0, 2)" :key="tag.id" class="tag">{{ tag.name }}</text>
      </view>
      <view class="product-price">
        <text class="current-price">¥{{ formatPrice(product.price) }}</text>
        <text v-if="product.originalPrice && product.originalPrice > product.price" class="original-price">¥{{ formatPrice(product.originalPrice) }}</text>
      </view>
      <view class="product-footer">
        <text class="sales">已售{{ product.sales || 0 }}</text>
        <view v-if="cartCount > 0" class="cart-qty-control" @click.stop>
          <text class="qty-btn minus" @click="decreaseCart">-</text>
          <text class="qty-num">{{ cartCount }}</text>
          <text class="qty-btn plus" @click="addToCart">+</text>
        </view>
        <view v-else class="add-cart" @click.stop="addToCart">
          <text class="icon">+</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { productApi, cartApi } from '@/api/index.js';
import common from '@/utils/common.js';
import storage from '@/utils/storage.js';

// 定义props
const props = defineProps({
  product: {
    type: Object,
    required: true
  },
  cartCount: {
    type: Number,
    default: 0
  }
});

// 定义emits
const emit = defineEmits(['cart-updated']);

// 格式化价格
const formatPrice = (price) => {
  return common.formatPrice(price);
};

// 跳转到商品详情
const goToDetail = () => {
  uni.navigateTo({
    url: `/pages/product/detail?id=${props.product.id}`
  });
};

// 添加到购物车
const addToCart = async () => {
  const token = storage.getToken();
  if (!token) {
    uni.navigateTo({
      url: '/pages/login/login'
    });
    return;
  }
  
  try {
    common.showLoading('添加中...');
    
    // 获取商品SKU
    const skuRes = await productApi.getProductSkus(props.product.id);
    if (skuRes.data && skuRes.data.length > 0) {
      const defaultSku = skuRes.data[0];
      
      await cartApi.addToCart({
        productId: props.product.id,
        skuId: defaultSku.id,
        quantity: 1
      });
      
      common.showSuccess('添加成功');
      
      // 触发购物车更新事件
      emit('cart-updated');
    } else {
      common.showError('商品暂无库存');
    }
  } catch (error) {
    console.error('添加购物车失败:', error);
    common.showError('添加失败:' + error.msg);
  } finally {
    common.hideLoading();
  }
};

// 减少购物车商品数量
const decreaseCart = async () => {
  if (props.cartCount <= 0) return;
  try {
    // 获取商品SKU
    const skuRes = await productApi.getProductSkus(props.product.id);
    if (skuRes.data && skuRes.data.length > 0) {
      const defaultSku = skuRes.data[0];
      // 先获取购物车项ID
      const cartRes = await cartApi.getCart();
      if (cartRes.code === 200 && cartRes.data && cartRes.data.items) {
        const cartItem = cartRes.data.items.find(item => item.product.id === props.product.id && item.sku.id === defaultSku.id);
        if (cartItem) {
          if (cartItem.quantity > 1) {
            await cartApi.updateCartItem(cartItem.id, { quantity: cartItem.quantity - 1 });
          } else {
            await cartApi.deleteCartItem(cartItem.id);
          }
          emit('cart-updated');
        }
      }
    }
  } catch (error) {
    console.error('减少购物车商品失败:', error);
    common.showError('操作失败:' + error.msg);
  }
};
</script>

<style scoped>
.product-card {
  background: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 20rpx;
  box-sizing: border-box;
  min-width: 0;
}

.product-image {
  position: relative;
  width: 100%;
  height: 300rpx;
}

.product-image .product-img-inner {
  width: 100%;
  height: 100%;
}

.new-tag {
  position: absolute;
  top: 10rpx;
  left: 10rpx;
  background: #ff4757;
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
}

.discount-tag {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  background: #ff6b35;
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
}

.product-info {
  padding: 20rpx;
}

.product-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-desc {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-tags {
  margin-bottom: 10rpx;
}

.tag {
  display: inline-block;
  background: #f0f0f0;
  color: #666;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
  margin-right: 10rpx;
}

.product-price {
  margin-bottom: 15rpx;
}

.current-price {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff4757;
  margin-right: 10rpx;
}

.original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
}

.product-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sales {
  font-size: 22rpx;
  color: #999;
}

.add-cart {
  width: 50rpx;
  height: 50rpx;
  background: #ff4757;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon {
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
}

.cart-qty-control {
  display: flex;
  align-items: center;
  background: #fff0f0;
  border-radius: 25rpx;
  padding: 0 10rpx;
  height: 50rpx;
}
.qty-btn {
  font-size: 32rpx;
  color: #ff4757;
  padding: 0 10rpx;
  font-weight: bold;
  user-select: none;
}
.qty-btn.minus {
  cursor: pointer;
}
.qty-btn.plus {
  cursor: pointer;
}
.qty-num {
  font-size: 28rpx;
  color: #333;
  min-width: 36rpx;
  text-align: center;
}
</style> 